package com.filldream.fastboot.common.okutil.stock.cf;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.filldream.fastboot.common.entity.db.CfAnn;
import com.filldream.fastboot.common.entity.db.CfArticle;
import com.filldream.fastboot.common.entity.db.CfNews;
import com.filldream.fastboot.common.entity.db.CfReport;
import com.filldream.fastboot.common.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.*;

@Slf4j
public class EastCfUtil {

    /**
     * 拉去某只股票的东财资讯
     * @param stockCode
     * @return
     */
    public static List<CfArticle> getArticles(String stockCode) {
        HttpRequest post = HttpUtil.createPost("https://guba.eastmoney.com/api/getData?code="+stockCode+"&path=webarticlelist/api/Article/Articlelist");
        Map<String, String> headMap = new HashMap<>();
        headMap.put("Accept", "application/json, text/plain, */*");
        headMap.put("Accept-Encoding", "gzip, deflate, br");
        headMap.put("Accept-Language", "zh-CN,zh;q=0.9");
        headMap.put("Connection", "keep-alive");
        headMap.put("Content-Length", "162");
        headMap.put("Content-Type", "application/x-www-form-urlencoded");
        headMap.put("Origin", "https://guba.eastmoney.com");
        headMap.put("Referer", "https://guba.eastmoney.com/list,"+stockCode+",1,f.html");
        headMap.put("Sec-Fetch-Dest", "empty");
        headMap.put("Sec-Fetch-Mode", "cors");
        headMap.put("Sec-Fetch-Site", "same-origin");
        headMap.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36");
        headMap.put("sec-ch-ua", "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"");
        headMap.put("sec-ch-ua-mobile", "?0");
        headMap.put("sec-ch-ua-platform", "\"Windows\"");
        headMap.put("Cookie", "qgqp_b_id=ce8c381899135716c17e4cdb6a26fcda; listtype=1; HAList=ty-171-US10Y-%u7F8E%u56FD10%u5E74%u671F%u56FD%u503A%2Cty-0-159338-%u4E2D%u8BC1A500ETF%2Cty-1-560510-%u4E2D%u8BC1A500ETF%2Cty-0-159682-%u521B%u4E1A50ETF%2Cty-133-USDCNH-%u7F8E%u5143%u79BB%u5CB8%u4EBA%u6C11%u5E01%2Cty-171-CN30Y-%u4E2D%u56FD30%u5E74%u671F%u56FD%u503A%2Cty-0-002456-%u6B27%u83F2%u5149%2Cty-1-000001-%u4E0A%u8BC1%u6307%u6570%2Cty-104-CN00Y-A50%u671F%u6307%u5F53%u6708%u8FDE%u7EED; websitepoptg_api_time=1732172921410; st_si=45366582731117; st_pvi=73211186471453; st_sp=2024-09-29%2011%3A00%3A22; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink; st_sn=6; st_psi=20241121152019544-117001356556-2914829822; st_asi=20241121152019544-117001356556-2914829822-gb.ggb.zxq-1");
        post.addHeaders(headMap);
        post.form("param", "code="+stockCode+"&type=1&p=1&ps=80&sorttype=0");
        post.form("plat", "Web");
        post.form("path", "webarticlelist/api/Article/Articlelist");
        post.form("env", "2");
        post.form("version", "2022");
        post.form("product", "Guba");
        try{
            String json = post.execute().body();
            log.info("获取东财资讯结果:{}",json.substring(0,20));
            JSONObject jsonObject = JSONObject.parseObject(json);
            String me = jsonObject.getString("me");
            if( me.equals("操作成功") ){
                if( jsonObject.containsKey( "re" ) ){
                    JSONArray list = jsonObject.getJSONArray("re");
                    List<CfArticle> cfArticles = JsonUtil.fromJosnArray(JsonUtil.toJson(list), CfArticle.class);
                    return cfArticles;
                }
            }
        }catch (Exception e){
            log.warn("获取东财资讯失败", e);
        }
        return Collections.emptyList();
    }

    /**
     * 东财研报
     * @param stockCode
     * @return
     */
    public static List<CfReport> getReport(String stockCode) {
        String html = HttpUtil.get("https://data.eastmoney.com/report/" + stockCode + ".html");
        Document htmlDocument = Jsoup.parse(html);
        Elements scriptDocuments = htmlDocument.getElementsByTag("script");
        for (Element scriptDocument : scriptDocuments) {
            String scriptContent = scriptDocument.html();
            if( scriptContent.contains("initdata") ){
                String json = scriptContent.substring(scriptContent.indexOf("initdata")+11,scriptContent.lastIndexOf("};")+1);
                JSONObject jsonObject = JSONObject.parseObject(json);
                if( jsonObject.containsKey("data") ){
                    JSONArray arrayJson = jsonObject.getJSONArray("data");
                    List<CfReport> cfReportList = JsonUtil.fromJosnArray(arrayJson.toString(), CfReport.class);
                    return cfReportList;
                }
            }
        }
        return new LinkedList<>();
    }

    /**
     * 东财公告
     * @param stockCode
     * @return
     */
    public static List<CfAnn> getAnn(String stockCode){
        try {
            String json = HttpUtil.get("https://np-anotice-stock.eastmoney.com/api/security/ann?page_size=50&page_index=1&ann_type=A&client_source=web&stock_list=" + stockCode + "&f_node=0&s_node=0");
            JSONObject jsonObject = JSONObject.parseObject(json);
            if (jsonObject.containsKey("data")) {
                JSONObject dataJsonObject = jsonObject.getJSONObject("data");
                if (dataJsonObject.containsKey("list")) {
                    JSONArray listJsonArray = dataJsonObject.getJSONArray("list");
                    List<CfAnn> cfAnnList = JsonUtil.fromJosnArray(listJsonArray.toString(), CfAnn.class);
                    cfAnnList.stream().forEach(t -> {
                        t.setStockCode(t.getCodes().get(0).getStockCode());
                    });
                    return cfAnnList;
                }
            }
        }catch (Exception e){
            log.warn("获取东财公告失败", e);
        }
        return new LinkedList<>();
    }

    /**
     * 获取东财新闻
     * @return
     */
    public static List<CfNews> getNews(){
        try {
            String json = HttpUtil.get("https://np-listapi.eastmoney.com/comm/web/getNewsByColumns?client=web&biz=web_news_col&column=344&order=1&needInteractData=0&page_index=1&page_size=25&req_trace=1732773173926&fields=code,showTime,title,mediaName,summary,image,url,uniqueUrl,Np_dst&types=1,25&_=1732773173927");
            JSONObject jsonObject = JSONObject.parseObject(json);
            if (jsonObject.containsKey("code") && jsonObject.getString("code").equals("1")) {
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
                List<CfNews> newsList = JsonUtil.fromJosnArray(jsonArray.toString(), CfNews.class);
                return newsList;
            }
        }catch (Exception e){
            log.warn("获取东财新闻失败", e);
        }
        return new LinkedList<>();
    }

}
